package com.pesking.core.sqlparser.processor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;
import com.pesking.core.util.StringUtils;
import com.pesking.unified.auth.DataRightResourceInfo;
import com.pesking.unified.auth.PopedomManage;

public class DataRightStringSqlParameterHandler extends SqlParameterProcessor {
	@Override
	public String getTitle() {
		return "数据权限参数";
	}

	@Override
	public String getDescription() {
		return this.getTitle() +  "，根据当前用户所拥的数据权限自动生成IN语句形式,比如:('1','2','3','4')形式";
	}

	@Override
	public void handle(StringBuilder sbSQL, Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		String name = sqlParameter.getName();
		String userId = PopedomManage.getCurrentUserId();
		if (!StringUtils.isBlank(userId)){
			List<DataRightResourceInfo> set = PopedomManage.getPopedomService().getDataRights(userId, name);
			if (set != null && set.size() > 0){
				Iterator<DataRightResourceInfo> it = set.iterator();
				sbSQL.append("(");
				boolean first = true;
				while(it.hasNext()){
					DataRightResourceInfo v = it.next();
					String value = formatValue(v.getId());
					if (!StringUtils.isBlank(value)){
						value = StringUtils.replace(value, "'", "''");
						if (first){
							first = false;
							sbSQL.append("'").append(v).append("'");
						}
						else{
							sbSQL.append(",'").append(v).append("'");
						}
					}
				}
				sbSQL.append(")");
			}
			else{
				sbSQL.append("(null)");
			}
		}
		else{
			sbSQL.append("(null)");
		}
	}

	
	public void setParameter(Connection connection,
			PreparedStatement ps, int index, String paramValue)
			throws SQLException {
		
	}

	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"DR_S"});
	}
}
